package com.ht.config.security;

import com.ht.config.security.handler.*;
import com.ht.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * @ProjectName: ht
 * @ClassName: SecurityConfig
 * @Author: hejialun
 * @Description: security配置类
 * @Date: 2021/6/22 11:56
 */
@Configuration
public class SecurityConfig {
    @Autowired
    LocalAuthenticationEntryPointHandler authenticationEntryPoint;//未登陆时返回 JSON 格式的数据给前端（否则为 html）
    @Autowired
    private MyUserDetailsService myUserDetailsService;
    @Autowired
    private LocalAuthenticationSuccessHandler localAuthenticationSuccessHandler;    //登录成功处理
    @Autowired
    private LocalAuthenticationFailureHandler localAuthenticationFailureHandler;    //登录失败处理
    @Autowired
    private LocalAccessDeniedHandler localAccessDeniedHandler;    //无权访问处理
    @Autowired
    private LocalLogoutSuccessHandler localLogoutSuccessHandler;    //退出登录

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;  //jwt过滤器


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .httpBasic(httpBasic -> httpBasic.authenticationEntryPoint(authenticationEntryPoint))
                .formLogin(form -> form
                        .successHandler(localAuthenticationSuccessHandler)
                        .failureHandler(localAuthenticationFailureHandler)
                        .permitAll()
                )
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                "/css/**",
                                "/lib/**",
                                "/core/**",
                                "/img/**",
                                "/login.html",
                                "/v3/api-docs/**",
                                "/swagger-ui/**",
                                "/swagger-ui.html",
                                "/socketServer/**",
                                "/doc.html#/**",
                                "/doc.html#/home",
                                "/weixin/**",
                                "/wxlogin.html",
                                "/imgView.html",
                                "/sys-login/login",
                                "/sys-login/wxLogin",
                                "/sys-login/getCode",
                                "/sys-login/getEmailCode/**",
                                "/sys-login/register",
                                "/common/test/**",
                                "/bus-room-user/findLoginUserLatelyOpenRoom"
                        ).permitAll()
                        .anyRequest().authenticated()
                )
                .rememberMe(rememberMe -> rememberMe
                        .tokenValiditySeconds(60)
                        .userDetailsService(myUserDetailsService)
                        .rememberMeParameter("rememberMe")
                        .rememberMeCookieName("rememberMe-cookie")
                )
                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .logoutSuccessHandler(localLogoutSuccessHandler)
                        .permitAll()
                )
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(authenticationEntryPoint)
                        .accessDeniedHandler(localAccessDeniedHandler)
                );

        // 加入JWT过滤器，放到UsernamePasswordAuthenticationFilter之前执行
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    // 如果后续需要手动注入AuthenticationManager可以这样写
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

}